package com.hnkywl.sts.action.sys;

import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.entity.organ.Zyf;
import com.hnkywl.sts.entity.sys.Zdkhz;
import com.hnkywl.sts.service.organ.QyjgService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.sys.ZdkhzService;
import com.hnkywl.sts.util.POIUtil;
import jxl.Sheet;
import jxl.Workbook;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.sts.action.sfgl
 * 类描述:    控货价
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Namespace("/sys/zdkhz")
public class ZdkhzAction extends SimpleActionSupport {
    private ZdkhzService zdkhzService;
    private QyjgService qyjgService;
    private int page;
    //分页组件 页面大小
    private int rows = 10;
    private String sysDate;
    private File upload;
    private Date zdkhzStartDate;
    private Date zdkhzEndDate;
    private String zdkhzKh;
    private Long id;
    private String zdkhz;

    @Action("zdkhz")
    public String zdkhz() {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        sysDate = simple.format(new Date());
        return SUCCESS;
    }

    // 最低控货值的查询分页显示
    @Action("zdkhzList")
    public void zdkhzList() {
        if (zdkhzStartDate != null)
            zdkhzStartDate = convertDate(zdkhzStartDate, true);
        if (zdkhzEndDate != null)
            zdkhzEndDate = convertDate(zdkhzEndDate, false);
        this.renderJson(this.zdkhzService.findAllZdkhzList(zdkhzKh, zdkhzStartDate, zdkhzEndDate, page, rows));
    }


    @Action("save_zdkhz")
    public void saveKhj() {
        try {
            if (zdkhz.matches("[\\d.]+")) {
                try {
                    Zdkhz saveZdkhz = this.zdkhzService.saveZdkhz(id, zdkhz);
                    renderJson("{\"statusCode\":200,\"message\":\"质押方最低控货值：" + saveZdkhz.getZyf().getQc() + "，修改成功!\"}");
                } catch (Exception e) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"值太大请检查后修改!\"}");
                }
            } else {
                renderText("{\"statusCode\":\"300\", \"message\":\"请输入数字！\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":300,\"message\":\"" + e.getMessage() + "\"}");
        }

    }

    // 导出质押方信息
    @Action("zdkhz_export")
    public String zdkhz_export() {
        List<Map> qyjgList = this.zdkhzService.findExportQyjgZdkhz();
        if (null != qyjgList && qyjgList.size() > 0) {
            //第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("sheet1");
            POIUtil poiUtil = new POIUtil(wb);
            //设置列宽
            sheet.setDefaultRowHeightInPoints(15);
            sheet.setDefaultColumnWidth((short) 12);
            sheet.setColumnWidth((short) 0, (short) (20 * 512));
            sheet.setColumnWidth((short) 1, (short) (20 * 512));
            sheet.setColumnWidth((short) 2, (short) (20 * 512));
            //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            row.setHeightInPoints(36);
            //第四步，创建单元格，并设置值表头  设置表头居中
            HSSFCellStyle titleStyle = poiUtil.createTitleHSSFCellStyle(wb);
            HSSFCell titleCell = row.createCell((short) 0);
            titleCell.setCellStyle(titleStyle);
            titleCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            titleCell.setCellValue("最低控货值文件");
            sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 2));
            //生成第一行数据...表头
            HSSFCellStyle headerStyle = poiUtil.createHeader3HSSFCellStyle(wb);
            poiUtil.fillRow(sheet, headerStyle, 1, "质押方全称", "质押方简称", "最低控货值");
            //生成从第二行开始的企业机构数据
            for (int i = 2; i < qyjgList.size() + 2; i++) { //从第三行开始导入
                poiUtil.fillRow(sheet, headerStyle, i, qyjgList.get(i - 2).get("QC"), qyjgList.get(i - 2).get("JC"), qyjgList.get(i - 2).get("zdkhz"));
            }
            try {
                response.setContentType("application/x-download");
                String filedisplay = new String(("最低控货值批量导入.xls").getBytes("gb2312"), "iso8859-1");
                response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
                wb.write(response.getOutputStream());
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
                renderText("位置异常，导出失败" + e.getMessage());
            }
        }
        return null;
    }

    // 控货价批量导入
    @Action("zdkhz_import")
    public void zdkhz_import() {
        try {
            // 导入数据
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
            Workbook book = Workbook.getWorkbook(upload);
            //  获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            //获取总行数
            int rows = sheet.getRows();
            List<Zdkhz> zdkhzList = new ArrayList<Zdkhz>();
            for (int i = 2; i < rows; i++) { //从第三行开始导入
                Zdkhz temp = new Zdkhz();
                if (sheet.getCell(0, i) != null && StringUtils.isNotEmpty(sheet.getCell(0, i).getContents())) {//第一列 编码
                    String qcName = sheet.getCell(0, i).getContents().toString();
                    Zyf zyf = this.qyjgService.findZyfByQc(qcName);
                    if (null == zyf) {
                        renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行没有查询质押方信息\"}");
                        return;
                    } else {
                        temp.setZyf(zyf);
                    }
                } else {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行质押方为空\"}");
                    return;
                }
                Double jg;
                if (sheet.getCell(2, i) == null || StringUtils.isEmpty(sheet.getCell(2, i).getContents())) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "最低控货值为空\"}");
                    return;
                } else if (!sheet.getCell(2, i).getContents().matches("[\\d.]+")) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "最低控货值不为数字\"}");
                    return;
                } else {
                    jg = Double.parseDouble(sheet.getCell(2, i).getContents().toString());
                    temp.setZdkhz(jg);
                }
                temp.setDrrq(new Date());
                temp.setCreateUser(YgService.getCurrentYg());
                temp.setCreateOrgan(YgService.getCurrentYg().getZggs());
                temp.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                temp.setDateCreated(new Date());
                temp.setLastUpdated(new Date());
                zdkhzList.add(temp);
            }
            zdkhzService.saveOrUpdateZdkhz(zdkhzList);
            renderText("{\"statusCode\":\"200\", \"message\":\"最低控货值批量导入成功！\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    /**
     * @param date
     * @param flag true:当天00:00:00   false:第二天00:00:00
     * @return
     */
    private Date convertDate(Date date, boolean flag) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        if (!flag)
            gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.HOUR, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        return gc.getTime();
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getSysDate() {
        return sysDate;
    }

    public void setSysDate(String sysDate) {
        this.sysDate = sysDate;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public Date getZdkhzStartDate() {
        return zdkhzStartDate;
    }

    public void setZdkhzStartDate(Date zdkhzStartDate) {
        this.zdkhzStartDate = zdkhzStartDate;
    }

    public Date getZdkhzEndDate() {
        return zdkhzEndDate;
    }

    public void setZdkhzEndDate(Date zdkhzEndDate) {
        this.zdkhzEndDate = zdkhzEndDate;
    }

    public String getZdkhzKh() {
        return zdkhzKh;
    }

    public void setZdkhzKh(String zdkhzKh) {
        this.zdkhzKh = zdkhzKh;
    }

    public String getZdkhz() {
        return zdkhz;
    }

    public void setZdkhz(String zdkhz) {
        this.zdkhz = zdkhz;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }


    @Autowired
    public void setZdkhzService(ZdkhzService zdkhzService) {
        this.zdkhzService = zdkhzService;
    }

    @Autowired
    public void setQyjgService(QyjgService qyjgService) {
        this.qyjgService = qyjgService;
    }
}
